package combo

import (
	"context"

	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/combo"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/utils/dberrorhandler"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/errorx"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateComboLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateComboLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateComboLogic {
	return &CreateComboLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateComboLogic) CreateCombo(in *pancakebot.ComboInfo) (*pancakebot.BaseIDResp, error) {

	if in.Name != nil {
		exists, err := l.svcCtx.DB.Combo.Query().Where(combo.NameEqualFold(*in.Name)).Exist(l.ctx)
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
		}
		if exists {
			return nil, errorx.NewInvalidArgumentError("combo.go.nameExist")
		}
	}

	query := l.svcCtx.DB.Combo.Create().
		SetNotNilName(in.Name).
		SetNotNilWeight(in.Weight).
		SetNotNilCalories(in.Calories).
		SetNotNilPrice(in.Price).
		SetNotNilImgAddr(in.ImgAddr)

	if in.TotalSales != nil {
		query.SetNotNilTotalSales(pointy.GetPointer(int(*in.TotalSales)))
	}

	result, err := query.Save(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	return &pancakebot.BaseIDResp{Id: result.ID, Msg: errormsg.CreateSuccess}, nil
}
